package thread.local;

import com.alibaba.fastjson.JSON;
import org.junit.Test;

/**
 * threadLocal问题
 *
 * @author hui.wang
 * @since 18 November 2018
 */
public class ThreadLocalde {

    static ThreadLocal<String> THREAD_LOCAL = new ThreadLocal<>();
    static ThreadLocal<Integer> THREAD_LOCAL2 = new ThreadLocal<>();
    static ThreadLocal<String> THREAD_LOCAL3 = new ThreadLocal<>();

    private static final ThreadLocal<ThreadLocalContext> threadlocalcontext = ThreadLocal.withInitial(ThreadLocalContext::new);

    public static void main(String[] args){
        String  tt = new String("a");
        ThreadLocal<String> ttThreadLocal = ThreadLocal.withInitial(()->tt);
        Thread t1 = new Thread(()->{ });
        t1.start();
        try {
            t1.join();
            System.out.println(JSON.toJSONString(tt));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void Test(){
        System.out.println();

        THREAD_LOCAL2.set(1);
        THREAD_LOCAL3.set("盲從");

        print();
    }

    private void print() {

        System.out.println(THREAD_LOCAL2.get());
        System.out.println(THREAD_LOCAL3.get());

    }
}

class A {
    public void run() {
        System.out.println("=========方式1==============");
        System.out.println("thread name :" + Thread.currentThread().getName());
        System.out.println("A get ThreadLocal :" + ThreadLocalde.THREAD_LOCAL.get());
        new B().run();
    }
}

class B {
    public void run() {
        System.out.println("************");
        System.out.println("thread name :" + Thread.currentThread().getName());
        System.out.println("B get ThreadLocal :" + ThreadLocalde.THREAD_LOCAL.get());
    }
}

class C {
    public void run() {
        System.out.println("=========方式2==============");
        System.out.println("thread name :" + Thread.currentThread().getName());
        System.out.println("C get ThreadLocal :" + ThreadLocalde.THREAD_LOCAL.get());
        new Thread(new D()::run).start();
    }
}

class D {
    public void run() {
        System.out.println("************");
        System.out.println("thread name :" + Thread.currentThread().getName());
        System.out.println("D get ThreadLocal :" + ThreadLocalde.THREAD_LOCAL.get());
    }
}